<template>
  <section class="todoapp">
    <hm-header @handelAdd="addObj"></hm-header>
    <hm-main
      :list="showList"
      @change-event="changeEvent"
      @remove-item-event="remove"
      @change-All-event="allIn"
    ></hm-main>
    <hm-footer
      :list="list"
      @clear-item-event="clearItem"
      :status="status"
      @change-status-event="status = $event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/active": "active",
  "#/completed": "completed",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [],
      status: obj[location.hash] || "all",
    };
  },
  methods: {
    // 选中
    changeEvent(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },
    // 删除
    remove(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    // 全选反选
    allIn(value) {
      return this.list.filter((item) => (item.done = value));
    },
    // 添加
    addObj(name) {
      const obj = {
        id: this.list.length === 0 ? 1 : this.list.slice(-1)[0].id + 1,
        name,
        done: false,
      };
      this.list.push(obj);
    },
    // 清除已完成
    clearItem() {
      this.list = this.list.filter((item) => !item.done);
    },
  },
  watch: {
    list: {
      deep: true,
      handler(value) {
        localStorage.setItem("list", JSON.stringify(value));
      },
    },
  },
  computed: {
    showList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "active") {
        return this.list.filter((item) => !item.done);
      } else {
        return this.list.filter((item) => item.done);
      }
    },
  },
};
</script>

<style></style>
